package cn.otrue.patienthealthmanager.http;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import cn.otrue.patienthealthmanager.HealthApplication;
import cn.otrue.patienthealthmanager.bean.TransferParameter;
import cn.otrue.patienthealthmanager.blowfish.Blowfish;
import cn.otrue.patienthealthmanager.utils.MyConst;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;

/**
 * login相关的网络通讯
 * 
 * @author G
 * 
 */
public class HttpServer {

	public static Gson gson = new Gson();
	public static Blowfish blowfish = new Blowfish();
	static {
		blowfish.setKey(HttpCons.BLOWFISH_KEY);
	}

	// 整体流程
	public void post(String url, TransferParameter parameter,
			final Handler handler) {
		if (!TextUtils.isEmpty(MyConst.getACCOUNT())) {
			parameter.setUsername(MyConst.getACCOUNT());
		}
		parameter.setLogintoken(MyConst.TOKEN);
		parameter.setChannelId(HttpCons.ANDROID_PATIENT_CHANNEL);
		parameter.setLatitude(HealthApplication.getInstance().getLatitude());
		parameter.setLongitude(HealthApplication.getInstance().getLongitude());
		RequestParams params = new RequestParams();
		String encryptedPassword = blowfish.encrypt(gson.toJson(parameter));

		params.addBodyParameter("TransferParameter", encryptedPassword);

		final Message msg = new Message();
		final Bundle data = new Bundle();

		HttpAsyncUtil.post(HttpAsyncUtil.getUrl(url), params,
				new MyRequestCallBack(msg, data, handler) {
					@Override
					public void onSuccess(ResponseInfo<String> json) {
						String jsonStr = json.result;
						if (jsonStr.contains("{")) {

							try {
								// 转换响应字符串为JsonObject
								JsonObject result = new JsonParser().parse(
										json.result).getAsJsonObject();
								// 得到状态码state
								String state = result.get(HttpCons.STATE)
										.getAsString();
								// 存储state到data(Bundle类型)中
								data.putString(HttpCons.STATE, state);
								// 得到data
								String dataStr = result.get(HttpCons.DATA)
										.toString();
								if (!dataStr.equals("null")) {
									// 存储dataStr到data中
									data.putString(HttpCons.DATA, dataStr);

								} else {
									data.putString(HttpCons.DATA, "");
								}

								// 当state值不为001时
								// 得到meaage(String类型)的值
								String message = result.get(HttpCons.MESSAGE)
										.getAsString();
								// 存储meaage到data中
								data.putString(HttpCons.MESSAGE, message);
							} catch (Exception e) {
								data.putString(HttpCons.STATE,
										HttpCons.STATE_ANALYTICAL_ERROR);
							}

						} else {
							data.putString(HttpCons.STATE,
									HttpCons.STATE_FORMAT_ERROR);
						}
						msg.setData(data);
						handler.sendMessage(msg);
					}
				});
	}
}
